<?php
/**
 * This file is part of Task Agile.
 * Task Agile is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License.
 * Task Agile is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with Task Agile.  If not, see <http://www.gnu.org/licenses/>.
 *
 * @category   TaskAgile
 * @package    Controller
 * @copyright  Copyright (c) 20010-2010 Estrada Virtual (http://estradavirtual.com.br)
 * @license    http://www.gnu.org/licenses/gpl.txt GPLv3
 * @version    $Id$
*/
class Task_TaskController extends Tev_Controller_Crud
{
    public function formAction()
    {
        $user = new User();
        $rowSetProjects = $user->find(Zend_Auth::getInstance()->getIdentity()->id)
                               ->current()->findProjectViaProjectUser();
        $projects = array('' => 'Selecione');
        foreach ($rowSetProjects as $rowProject) {
            $projects[$rowProject->id] = $rowProject->name;
        }
        $this->view->projects = $projects;
        unset($projects);

        // Type Task
        $typeTask = new TypeTask();
        $rowSetTypeTask = $typeTask->fetchAll(null, 'name');
        unset($typeTask);

        $typesTasks = array('' => 'Selecione');
        foreach ($rowSetTypeTask as $rowTypeTask) {
            $typesTasks[$rowTypeTask->id] = $rowTypeTask->name;
        }
        $this->view->typesTasks = $typesTasks;

        $task = new Task();
        if ($id = $this->_getParam('id', false)) {
            $rowTask = $task->find($id)->current();
        } else {
            $rowTask = $task->createRow();
        }
        $this->view->task 	   = $rowTask;
        $this->view->prioritys = $task->getPrioritys();
        $this->view->status    = $task->getStatus();
    }

    public function saveAction()
    {
        $task = new Task();
        if ($id = $this->_getParam('id', false)) {
            $rowTask = $task->find($id)->current();
        } else {
            $rowTask = $task->createRow();
            $rowTask->dt_register    = date('Y-m-d H:i:s');
            $rowTask->status         = Task::STATUS_ACTIVE;
            $rowTask->read           = Task::NOT_READ;
            $rowTask->fk_user        = Zend_Auth::getInstance()->getIdentity()->id;
            $rowTask->fk_user_create = Zend_Auth::getInstance()->getIdentity()->id;
        }
        $rowTask->fk_project  = $this->_getParam('fk_project');
        $rowTask->name        = $this->_getParam('name');
        $rowTask->description = $this->_getParam('description');
        $rowTask->priority    = $this->_getParam('priority');
        $rowTask->save();
        $this->_redirect('task/dashboard');
    }

    /**
     *  Visualizar como leitura a tarefa
     */
    public function seeAction()
    {
        $idTask = $this->_getParam('id');
        $idUser = Zend_Auth::getInstance()->getIdentity()->id;

        // @todo tratar caso não encontre registro
        $task = new Task();
        $rowTask    = $task->find($idTask)->current();
        $rowProject = $rowTask->findParentProject();

        // Check task read
        if ($idUser == $rowTask->fk_user && $rowTask->read != Task::READ) {
            $rowTask->read = Task::READ;
            $rowTask->save();
        }

        // Add comment preview
        if ($idUser != $rowTask->fk_user) {
            $session = new Zend_Session_Namespace('viewing');
            if (empty($session->task[$rowTask->id])) {
                $translate = Zend_Registry::get('Zend_Translate');
                $comment   = $translate->_('Viewing');
                $taskComment = new TaskComment();
                $taskComment->comment($idTask, $idUser, $comment);
            }
            $session->task[$rowTask->id] = true;
        }

        // Users
        $user = new User();
        $rowSetUsers = $user->fetchAll(null, 'name');
        unset($user);
        $users = array();
        foreach ($rowSetUsers as $rowUser) {
            $users[$rowUser->id] = $rowUser->name;
        }
        $this->view->users = $users;
        unset($users);

        // User project
        $rowSetUsers = $rowProject->findUserViaProjectUser();
        $usersProject = array();
        foreach ($rowSetUsers as $rowUser) {
            $usersProject[$rowUser->id] = $rowUser->name;
        }
        // Retira o usuário da tarefa
        unset($usersProject[$rowTask->fk_user]);
        $this->view->usersProject = $usersProject;

        $this->view->task      = $rowTask;
        $this->view->project   = $rowProject;
        $this->view->comments  = $rowTask->findTaskComment($task->select()->order('dt_register desc'));
        $this->view->prioritys = $task->getPrioritys();
    }

    public function closeAction()
    {
        $idTask = $this->_getParam('id');
        if (empty($idTask) || !Zend_Validate::is($idTask, 'Digits')) {
            // @todo gravar msg
            $this->_redirect('task/dashboard');
        }

        try {
            $task = new Task();
            $rowTask = $task->close($idTask, Zend_Auth::getInstance()->getIdentity()->id);
        } catch (Exception $e) {
            // @todo tratar o caso não consiga fechar a tarefa
        }

        // Send email
        $this->view->user          = $rowTask->findParentUser();
        $this->view->task          = $rowTask;
        $this->view->project       = $rowTask->findParentProject();
        $this->view->usuarioOrigem = Zend_Auth::getInstance()->getIdentity()->name;
        $emailBody = $this->view->render('email/task-closed.phtml');

        $mail = new Zend_Mail('UTF8');
        $translate = Zend_Registry::get('Zend_Translate');
        $mail->setSubject($translate->_('email-subject-task-closed'));
        $mail->setBodyHtml($emailBody);

        $rowProject = $rowTask->findParentProject();
        $rowSetUsers = $rowProject->findUserViaProjectUser();
        foreach ($rowSetUsers as $rowUser) {
            try {
                $mail->clearRecipients();
                $mail->addTo($rowUser->email, $rowUser->name);
                $mail->send();
            } catch (Exception $e) {
                // @todo tratar quando der erro de envio de email
            }
        }
        $this->_redirect('task/dashboard');
    }

    public function openAction()
    {
        $idTask = $this->_getParam('id');
        if (empty($idTask) || !Zend_Validate::is($idTask, 'Digits')) {
            // @todo gravar msg
            $this->_redirect('task/dashboard');
        }

        try {
            $task = new Task();
            $rowTask = $task->open($idTask, Zend_Auth::getInstance()->getIdentity()->id);
        } catch (Exception $e) {
            // @todo tratar o caso não consiga fechar a tarefa
        }

        $this->_redirect('task/dashboard');
    }

    public function commentAction()
    {
        $idTask = $this->_getParam('idTask');
        /*
        $task = new Task();
        $rowTask = $task->find($idTask)->current();
        if (Zend_Auth::getInstance()->getIdentity()->id != $rowTask->fk_user) {
            // @todo colocar msg
            $this->_redirect('task/task/see/id/' . $idTask);
        }*/
        /*
        if (Task::STATUS_FINISHED == $rowTask->status) {
            // @todo colocar msg
            $this->_redirect('task/task/see/id/' . $idTask);
        }
        */
        // @todo Tratar com escape de banco
        $comment = $this->_getParam('comment');
        $hours   = $this->_getParam('hours');

        $taskComment = new TaskComment();
        $taskComment->comment($idTask, Zend_Auth::getInstance()->getIdentity()->id, $comment, $hours);
        $this->_redirect('task/task/see/id/' . $idTask);
    }

    /**
     * Encaminha tarefa com mensagem
     */
    public function forwardAction()
    {
        $idTask  = $this->_getParam('idTask');
        $idTo    = $this->_getParam('to');
        $message = $this->_getParam('message');

        $user = new User();
        $rowUser = $user->find($idTo)->current();

        try {
            $task = new Task();
            $rowTask = $task->forward($idTask, Zend_Auth::getInstance()->getIdentity()->id, $rowUser);
        } catch (Exception $e) {
            // @todo tratar o caso não consiga fechar a tarefa
        }

        // Send email
        $this->view->user          = $rowUser;
        $this->view->task          = $rowTask;
        $this->view->project       = $rowTask->findParentProject();
        $this->view->usuarioOrigem = Zend_Auth::getInstance()->getIdentity()->name;
        $emailBody = $this->view->render('email/task-forward.phtml');

        $mail = new Zend_Mail('UTF8');
        $translate = Zend_Registry::get('Zend_Translate');
        $mail->setSubject($translate->_('email-subject-task-forward'));
        $mail->addTo($rowUser->email, $rowUser->name);
        $mail->setBodyHtml($emailBody);
        try {
            $mail->send();
        } catch (Exception $e) {
            // @todo tratar quando der erro de envio de email
        }
        $this->_redirect('task/dashboard');
    }

    public function inactivateAction()
    {
        $idTask  = $this->_getParam('id');

        try {
            $task = new Task();
            $rowTask = $task->inactivate($idTask);
        } catch (Exception $e) {
            // @todo tratar o caso não consiga congelar a tarefa
        }
        $this->_redirect('task/dashboard');
    }
}
